package com.demo.gulimall.order.config;

import com.alibaba.fastjson.JSON;
import com.demo.gulimall.order.entity.Order;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataUnit;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

/**
 * @author Chen Yuan
 * @create 2023-07-03  15:28
 */
@Slf4j
@Configuration
public class MyRabbitMQConfig {

	// 监听队列
	//@RabbitListener(queues = {"order.release.queue"})
	//public void queueListener(Order order, Channel channel, Message message) throws IOException {
	//	String create = DateFormatUtils.format(order.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
	//	String now = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
	//	log.info("==> queueListener - 接收到订单信息 - 准备关闭订单 - orderSn:{}, create:{}, now:{}", order.getOrderSn(), create, now);
	//
	//	// 手动确认消息
	//	channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
	//}


	// 创建延迟队列
	@Bean
	public Queue orderDelayQueue(){
		// 自定义的属性
		HashMap<String, Object> arguments = new HashMap<>();
		arguments.put("x-dead-letter-exchange", "order-event-exchange");
		arguments.put("x-dead-letter-routing-key", "order.release.order");
		arguments.put("x-message-ttl", 60*1000);

		// 参数: 名称, 是否持久化, 是否排他的(只要有连接正在使用, 其他连接就不能使用), 是否自动删除, 自定义的属性
		return new Queue("order.delay.queue", true, false, false, arguments);
	}

	// 创建死信队列
	@Bean
	public Queue orderReleaseQueue(){
		return new Queue("order.release.queue", true, false, false);
	}

	// 创建死信交换机
	@Bean
	public Exchange orderEventExchange(){

		return new TopicExchange("order-event-exchange", true, false);
	}

	// 创建订单时的绑定关系
	@Bean
	public Binding orderCreateBinding(){
		return new Binding("order.delay.queue", Binding.DestinationType.QUEUE, "order-event-exchange", "order.create.order", null);
	}

	// 创建死信绑定关系
	@Bean
	public Binding orderReleaseBinding(){
		return new Binding("order.release.queue", Binding.DestinationType.QUEUE, "order-event-exchange", "order.release.order", null);
	}

	// 与库存的延时队列进行绑定
	@Bean
	public Binding orderReleaseOtherBinding(){
		return new Binding("stock.release.queue", Binding.DestinationType.QUEUE, "order-event-exchange", "order.release.other.#", null);
	}

	// 秒杀队列
	@Bean
	public Queue orderSeckillOrderQueue(){
		return new Queue("order.seckill.order.queue", true, false, false);
	}

	@Bean
	public Binding orderSeckillOrderBinding(){
		return new Binding("order.seckill.order.queue", Binding.DestinationType.QUEUE, "order-event-exchange", "order.seckill.order", null);
	}

}
